/**
 * Created by liubin on 2017/6/2.
 */


var DtjTableStatus = function() {
    var that = {};

    //
    that.lastStep = -1;

    //录像msg
    that.replayMsgs = null;

    //录像type
    that.replayTypes = null;

    that.mTableStatus = null;

    that.isReconnect = false;

    //设置牌桌映像
    that.setTableStatus = function(tableStatus){
        that.mTableStatus = tableStatus;

        //记录是否是断线重连
        if (that.mTableStatus.Step != 0){
            that.isReconnect = false;
        }

        //在德州扑克里面才触发
        if (mo.sceneHelper.currentLayerName != "dtj"){
            return;
        }

        that.updateTableStatus();
    };


    that.setReconnectStatus = function (tableStatus) {
        that.mTableStatus = tableStatus;

        //记录是否是断线重连
        if (that.mTableStatus.Step == 0){
            that.isReconnect = true;
        }

        this.updateUserInfo();

        //断线重连
        that.setReconnet();

        //更新牌桌step
        mo.dtjTable.updateTableStep(that.mTableStatus.Step);

    };

    that.updateTableStatus = function () {

        this.updateUserInfo();

        //更新牌桌step
        mo.dtjTable.updateTableStep(that.mTableStatus.Step);

        that.updateStep();

    };


    that.updateStep = function () {

        if (that.mTableStatus.Step == 0){ //非打牌阶段

        }else if (that.mTableStatus.Step == 1) {
            //切锅，续锅
            if (that.mTableStatus.LastAction == null){
                var newAction = 0;
                var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
                if(mySeatUser.NewActionList.length > 0){
                    newAction = mySeatUser.NewActionList[0].code;
                    mo.dtjTable.mDtjTableUILayer.setQieGuoOrXuguoState(true, mySeatUser.IsHost, newAction);
                }else {
                    if(that.mTableStatus.GuoPoint > 0){
                        newAction = 3;
                        if(mySeatUser.Score > 60){
                            mo.gameMsgManager.sendActionRequestdtj(3, 1, []);
                        }else{
                            mo.gameMsgManager.sendActionRequestdtj(3, 0, []);
                        }
                    }else{
                        mo.gameMsgManager.sendActionRequestdtj(4, 1, []);
                        newAction = 4;

                    }
                    // mo.dtjTable.mDtjTableUILayer.setQieGuoOrXuguoState(true, false, newAction);
                }
            }
        }else if (that.mTableStatus.Step == 2) {
            //抢庄
            if (that.mTableStatus.LastAction == null){
                mo.dtjTable.mDtjTableUILayer.setMakeHost(true);

            }

        } else if (that.mTableStatus.Step == 3) {
            //加倍 显示牌墙
            if (that.mTableStatus.LastAction == null || that.mTableStatus.LastAction.code >= 3){
                //下注按钮
                var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];

                //如果是庄家就直接发送值
                if (mySeatUser.IsHost){
                    // that.sendMyBet([0, 0]);
                }else{
                    mo.dtjTable.mDtjTableUILayer.setBetInfo(mySeatUser.NewActionList);
                }
            }else if(that.mTableStatus.LastAction.code == 0){
                that.makeHost();
            }

        }else if (that.mTableStatus.Step == 4){ //打牌阶段

            var lastAction = that.mTableStatus.LastAction;
            var lastSeat = that.mTableStatus.LastActionSeat;
            var viewSeat = that.getViewForLogic(lastSeat - 1, that.mTableStatus.MySeat - 1);

            if (lastAction == null || lastAction.code == 1) {
                //发牌
                var validSeats = [];
                var seats = [false, false, false, false];
                var cardNums = [[], [], [], []];
                for (var seat = 0; seat < 4; seat++) {
                    var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                    var seatuser = that.mTableStatus["SeatUser" + (logicSeat + 1)];
                    validSeats.push(logicSeat);

                    if (seatuser != null) {
                        seats[seat] = true;
                        cardNums[seat] = seatuser.HandCards;
                    }
                }

                var sz = that.mTableStatus.SZ;
                var hostSeat = that.mTableStatus.HostSeat;

                var szNum = parseInt(sz / 10) + sz % 10;
                var firstSeat = that.getViewForLogic((hostSeat - 1 + szNum - 1) % validSeats.length, that.mTableStatus.MySeat - 1);

                //庄的位置
                mo.dtjTable.fapai(cardNums, firstSeat, sz);
                return;
            } else if (lastAction != null && lastAction.code == 0) {
                that.makeHost();
            } else if (lastAction != null && lastAction.code == 2) {
                //开牌
                var cardNums = lastAction.Cards;
                if(mo.dtjTable.mPlayerType == 0 || viewSeat == 0){
                    cardNums =  that.mTableStatus["SeatUser" + lastSeat].LastAction.Cards;
                }
                mo.dtjTable.setKaipaiSeat(viewSeat, cardNums);
            }

            that.checkTableDisplay();
        }
    };

    that.checkTableDisplay = function () {

    };

    that.makeHost = function () {
        var makeHost = [];
        var hostSeat = -1;
        for (var seat = 0; seat < 4; seat++){
            var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
            var seatuser = that.mTableStatus["SeatUser" + (logicSeat + 1)];
            if (seatuser != null){

                if(seatuser.MakeHostRate == 1){
                    makeHost.push(seat);
                }

                if(seatuser.IsHost){
                    hostSeat = seat;
                }
            }
        }

        var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
        mo.dtjTable.mDtjTableUILayer.playMakeHostAni(hostSeat, makeHost, mySeatUser);
    };


    that.setReconnet = function () {
        var tableStatus = mo.dtjTableStatus.mTableStatus;

        mo.dtjTable.updateLastPlayTimes();

        var UsedCards = tableStatus.UsedCards;
        if(!!UsedCards){
            mo.dtjTable.mDtjCardLayer.setUsedCards(UsedCards);
        }

        if (tableStatus.Step == 1){
            //切锅，续锅
            var newAction = 0;
            var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
            if(mySeatUser.NewActionList.length > 0){
                newAction = mySeatUser.NewActionList[0].code;
                mo.dtjTable.mDtjTableUILayer.setQieGuoOrXuguoState(true, mySeatUser.IsHost, newAction);
            }else {
                newAction = 3;

                // if(that.mTableStatus.GuoPoint > 0){
                //     newAction = 3;
                // }else{
                //     newAction = 4;
                // }
                mo.dtjTable.mDtjTableUILayer.setQieGuoOrXuguoState(true, false, newAction);
            }
        }

        if (tableStatus.Step == 2){
            //抢庄
            var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
            if (mySeatUser.LastAction == null){
                mo.dtjTable.mDtjTableUILayer.setMakeHost(true);
            }
        }

        if (tableStatus.Step == 3){
            var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
            if(!mySeatUser.IsHost){
                mo.dtjTable.mDtjTableUILayer.setBetInfo(mySeatUser.NewActionList);
            }
        }

        if (tableStatus.Step == 4){
            var hasOpenCard = [false, false, false, false];
            var cardNumss = [[], [], [], []];
            var handCards = [];

            for (var seat = 0; seat < 4; seat++){
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                var seatUser = that.mTableStatus["SeatUser" + (logicSeat + 1)];

                if (seatUser != null) {
                    var lastAction = seatUser.LastAction;
                    if (lastAction != null && lastAction.code == 2) {
                        hasOpenCard[seat] = true;
                        if(seat == 0 || lastAction.Cards.length == 2){
                            cardNumss[seat] = lastAction.Cards;
                        }
                    }

                    handCards.push(seatUser.HandCards);

                }else{
                    handCards.push([]);
                }
            }

            mo.dtjTable.mDtjTableUILayer.startTimeLeft();

            mo.dtjTable.mDtjCardLayer.setInhandCard(handCards);

            mo.dtjTable.mDtjCardLayer.setSelectedState(hasOpenCard, cardNumss);

        }
    };

    //抢庄，0不抢，1抢
    that.sendMakeHost = function (qiang) {
        if (that.mTableStatus.Step == 2){
            mo.gameMsgManager.sendActionRequestdtj(0, qiang, []);
        }
    },

    //选择自己下注筹码
    that.sendMyBet = function(betNums){
        if (that.mTableStatus.Step == 3){
            mo.gameMsgManager.sendActionRequestdtj(1, 0, betNums);
        }
    };

    //开牌
    that.sendKaiPai = function(cards){
        if (that.mTableStatus.Step == 4){
            var mySeatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
            var newActionList = mySeatUser.NewActionList;
            if (newActionList.length > 0){
                mo.gameMsgManager.sendActionRequestdtj(newActionList[0].code, newActionList[0].Rate, cards);
            }
        }
    };


    //更新用户信息
    that.updateUserInfo = function () {
        //牌局结束以后（剩余次数为0，step为0） 不显示用户ui变化
        if (that.mTableStatus.LeftPlayTimes == 0 && that.mTableStatus.Step == 0){
            return;
        }

        if(that.lastStep == 2 && that.mTableStatus.Step == 3){
            return;
        }

        if(that.lastStep == 2 && that.mTableStatus.Step == 4){
            return;
        }

        if (that.mTableStatus.TableID){
            var infos = [null, null, null, null, null];
            for (var seat = 0; seat < 4; seat++){
                var logicSeat = that.getLogicForView(seat, that.mTableStatus.MySeat - 1);
                infos[seat] = that.mTableStatus["SeatUser" + (logicSeat + 1)];
            }
            mo.dtjTable.mDtjTableUILayer.setTablePlayerInfos(infos);
        }else{
            //录像可能没有
        }
    };


    //加载录像
    that.setReplayMsg = function(rePlaydtj){
        that.replayMsgs = [];
        that.replayTypes = [];

        //设置录像时候自己的座位号
        var replayMySeat = 1;
        var roundEndedEvent = rePlaydtj.Result;
        for(var i = 1; i <= 4; i++){
            if (roundEndedEvent["SeatUser" + i] != null){
                if (roundEndedEvent["SeatUser" + i].user_info != null){
                    if (roundEndedEvent["SeatUser" + i].user_info.userid == mo.gameUserInfo.uid){
                        replayMySeat = i;
                        break;
                    }
                }
            }
        }
        roundEndedEvent.MySeat = replayMySeat;

        //牌桌映像数据
        for (var i = 0; i < rePlaydtj.Images.length; i++){
            var tableStatsdtj = rePlaydtj.Images[i];
            if(tableStatsdtj.Step != 4){
                continue;
            }

            if(tableStatsdtj.LastAction != null && tableStatsdtj.LastAction.code == 0){
                tableStatsdtj.LastAction = null;
            }

            //修改MySeat
            tableStatsdtj.MySeat = replayMySeat;

            that.replayMsgs.push(tableStatsdtj);
            that.replayTypes.push(2506);
        }

        //牌桌结算数据
        that.replayMsgs.push(rePlaydtj.Result);
        that.replayTypes.push(2508);
    };

    //播放录像
    that.playReplay = function(){
        if (that.replayMsgs.length > 0){
            var msg = that.replayMsgs.shift();
            var type = that.replayTypes.shift();

            var response = null;
            if (type == 2506){
                //牌桌映象
                response = new DtjTableStatsdtj();

            }else if (type == 2508){
                //牌桌结算
                response = new DtjRoundEndedEventdtj();
            }

            if (response){
                response.handleMsg(msg);
                response.log();
            }else{
                cc.warn("type:" + type + "未注册");
            }
            return true;
        }else{
            cc.log("录像播放完毕");
            return false;
        }

    };


    that.getLogicForView = function(view, myLogicSeat){
        var logic = (view + 4 + myLogicSeat) % 4;
        return logic;
    };

    that.getViewForLogic = function(logic, myLogicSeat){
        var view = (logic + 4 - myLogicSeat) % 4;
        return view;
    };

    //获取自己是否准备
    that.getMyIsReady = function(){
        var seatUser = that.mTableStatus["SeatUser" + that.mTableStatus.MySeat];
        return seatUser.State == 1;
    };


    //返回TableUserStats
    that.getTableUserStatsdtj = function(viewSeat){
        var seatUsers = [that.mTableStatus.SeatUser1, that.mTableStatus.SeatUser2, that.mTableStatus.SeatUser3, that.mTableStatus.SeatUser4, that.mTableStatus.SeatUser5];
        var logicSeat = that.getLogicForView(viewSeat, that.mTableStatus.MySeat - 1);

        return seatUsers[logicSeat];
    };

    //通过ui的返回玩家视图座位号
    that.getViewSeatForUid = function (uid) {
        var logicIndex = -1;
        for (var i = 0; i < 4; i++){
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser != null){
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid){
                    logicIndex = i;
                }
            }
        }
        if (logicIndex != -1){
            return that.getViewForLogic(logicIndex, that.mTableStatus.MySeat - 1);
        }else{
            return -1;
        }
    };


    //通过用户id获取用户性别
    that.getSexForUid = function(uid){
        var sex = 0;
        for (var i = 0; i < 4; i++){
            var seatUser = that.mTableStatus["SeatUser" + (i + 1)];
            if (seatUser != null && seatUser.user_info != null){
                if (seatUser.user_info.userid == uid || seatUser.user_info.nickname == uid){
                    sex = seatUser.user_info.sex;
                }
            }
        }
        return sex;
    };

    //通过视图座位号返回用户性别
    that.getSexForViewSeat = function(view){
        var sex = 0;
        var logicSeat = that.getLogicForView(view, that.mTableStatus.MySeat - 1);
        var seatUser = that.mTableStatus["SeatUser" + (logicSeat + 1)];
        if (seatUser != null && seatUser.user_info != null){
            sex = seatUser.user_info.sex;
        }
        return sex;
    };

    //通过逻辑座位号返回用户性别
    that.getSexForLogicSeat = function(seat){
        var sex = 0;
        var seatUser = that.mTableStatus["SeatUser" + (seat + 1)];
        if (seatUser != null && seatUser.user_info != null){
            sex = seatUser.user_info.sex;
        }
        return sex;
    };

    //获取玩家同ip信息
    that.getPlayerIpEqual = function(){
        var result = [];

        //记录ip
        var ipStruct = {};
        for (var i = 1; i <= 4; i++){
            var seatUser = that.mTableStatus["SeatUser" + i];
            if (seatUser != null && seatUser.user_info != null){
                var userInfo = seatUser.user_info;
                if (mo.gameHelper.getIsJson(userInfo.DeviceJson)) {
                    var deviceJson = JSON.parse(userInfo.DeviceJson);
                    var ip = deviceJson.ip;
                    if (ip != null && ip != "" && ip != "127.0.0.1") {
                        if (ipStruct[ip] == undefined) {
                            ipStruct[ip] = [];
                        }
                        ipStruct[ip].push(userInfo.nickname);
                    }
                }
            }
        }

        //分解出出现两次的用户
        for(var key in ipStruct){
            if (ipStruct.hasOwnProperty(key)) {
                if (ipStruct[key].length > 1){
                    var nicks = ipStruct[key];
                    for (var i = 0; i < nicks.length; i++){
                        var item = {};
                        item.nick = nicks[i];
                        item.ip = key;
                        result.push(item);
                    }
                }
            }
        }

        return result;
    };

    //返回玩家人数
    that.getPlayerCount = function(){
        var count = 0;
        for (var i = 1; i <=4; i++){
            var userSeat = that.mTableStatus["SeatUser" + i];
            if (userSeat != null){
                count++;
            }
        }
        return count;
    };

    return that;
}


mo.dtjTableStatus = new DtjTableStatus();